package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletContext;
import java.io.File;

@Controller
@RequestMapping("/file")
public class UploadController {

    @Autowired
    private ServletContext application;

    @RequestMapping("/upload")
    public String upload(@RequestParam("file") CommonsMultipartFile file,
                         @RequestParam("name") String name)throws Exception{
        System.out.println("UploadController.upload()");

        System.out.println("name = " + name);
        System.out.println("file = " + file);

        System.out.println("file.getName() = " + file.getName());
        System.out.println("file.getContentType() = " + file.getContentType());
        System.out.println("file.getOriginalFilename() = " + file.getOriginalFilename());
        System.out.println("file.getSize() = " + file.getSize());



//        String uploadDir=application.getRealPath("/WEB-INF/upload");

        String uploadDir=this.getClass().getClassLoader().getResource("").getPath();
        uploadDir=uploadDir.substring(0,uploadDir.lastIndexOf("/WEB-INF"))+"/WEB-INF/upload";


        System.out.println("uploadDir = " + uploadDir);
        
        file.transferTo(new File(uploadDir,file.getOriginalFilename()));

        return "redirect:/showUpload";
    }
}
